#pragma once
#include <sys/types.h>
#include <sys/ipc.h>
#include <string>
#include <unistd.h>
#include <cstdlib>
#include <sys/shm.h>
#include <iostream>


#define SIZE 1024
#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)
#define PATHNAME "."
#define PROJID 10
#define CREATER "CREATER"
#define USER "USER"



class Shm
{
public:
    Shm(std::string pathname, int projid, std::string usertype)
        : _pathname(pathname)
        , _projid(projid)
        , _usertype(usertype)
    {
        _key = ftok(_pathname.c_str(), _projid);
    }

private:
    void Creat()
    {
        _shmid = shmget(_key, SIZE, IPC_CREAT | IPC_EXCL | 0666);
        if (_shmid == -1)
        {
            ERR_EXIT("shm cerat :");
        }

        std::cout << "共享内存已经创建" << std::endl;
    }

    void Get()
    {
        _shmid = shmget(_key, SIZE, IPC_CREAT );
        if (_shmid == -1)
        {
            ERR_EXIT("shm get :");
        }

        std::cout << "共享内存已经获取" << std::endl;
    }

    void Dettach()
    {
        int ret = shmdt(_addr);
        if (ret == -1)
        {
            ERR_EXIT("Dettach :");
        }

        std::cout << "共享内存已经去关联" << std::endl;
    }

    void Destroy()
    {
        int ret = shmctl(_shmid, IPC_RMID, nullptr);
        if (ret == -1)
        {
            ERR_EXIT("creater delete :");
        }
        std::cout << "共享内存删除" << std::endl;
    }

public:
    void GetShm()
    {
        if (_usertype == USER)
        {
            Get();
        }
        else if (_usertype == CREATER)
        {
            Creat();
        }
    }
    void* GetAddr()
    {
        return _addr;
    }
    void Attach()
    {
        _addr = shmat(_shmid, nullptr, 0);
        if ((long long)_addr == -1)
        {
            ERR_EXIT("shm attach :");
        }

        std::cout << "共享内存已经挂载" << std::endl;
    }

    ~Shm()
    {
        std::cout << "调用到析构函数" << std::endl;
        if (_usertype == "USER")
        {
            Dettach();
        }
        else
        {
            Dettach();
            Destroy();
        }
    }

private:
    std::string _usertype;
    int _shmid;
    void *_addr;
    key_t _key;
    std::string _pathname;
    int _projid;
};
